package Logging;

require 5;

BEGIN	
{
	use TWM;
	use Data::Dumper;
}

sub new
{
	my $internalIP = &getInternalIP;
	my $self = {
		this_module_code => 'http_logging',
		isp => 0,
		local_interface => $internalIP->{inf}, 
		localip => $internalIP->{ip},
		squid_port => 3128
	};
	return bless $self;
}

sub DESTROY	{
	my $self = shift;
	delete $self->{$_} for (keys %$self);
	undef(%$self);
	undef $self;
}


##################################################
# Get interace code by ISP code
##################################################
sub getInterfacebyISPCode
{
	my ($self, $code) = (shift, shift);
	if (ref $self->{isp} ne 'HASH')
	{
		$self->{isp} = &getISP;
	}
	my $isp = &getISP;
	for (keys %{$self->{isp}})
	{
		return $self->{isp}->{$_}->{inf} if ($self->{isp}->{$_}->{code} eq $code);
	}
	return '';
}



##################################################
# Returns squid setiings hash with port number key
# $h = 
# {
#   '3128' => {
#			port => '3128',
#			inf => 'ppp3',
#			isp => 'ByFly'
#			log_folder => '/home/squid/logs',
#			access_log => 'access.log',
#			config => '/etc/squid/squid.conf'
#			enabled => '1'
#             },
#   '3129' => {.....................}
# }
# 
##################################################
sub getSquidsSettings
{
	my ($self) = (shift);
	my $list;
	my $node = getConfigNode("squid_settings", "$ck{twmfolder}modules/$self->{this_module_code}/module.conf");
	my $count = 0;
	foreach (keys %{$node->{html_control}->{columns}})
	{
		$count ++;
	}
	$index = 0;
	my @val = split(/\|/, $C->{$self->{this_module_code}}->{squid_settings});
	while ($index < $#val)
	{
		my $item = {
			port => $val[$index]||'',
			isp => $val[$index+1]||'',
			inf => $self->getInterfacebyISPCode($val[$index+1]||''),
			log_folder => $val[$index+2]||'',
			access_log => $val[$index+3]||'',
			config => $val[$index+4]||'',
			enabled => $val[$index+5]||''
		};
		$index += $count;
		$list->{$item->{port}} = $item if ($item->{port});
	}
	$list;
}

sub runRules
{
	my ($self, $rule_type, $ip) = (shift,shift,shift);
	if ($self->{squid_port})
	{
		run_script("$ck{iptables} -t nat -$rule_type PREROUTING -i $self->{local_interface} -p tcp -s $ip ! -d $self->{localip} --dport 80 -j REDIRECT --to-port $self->{squid_port}");
		run_script("$ck{iptables} -$rule_type INPUT -p tcp -s $ip --dport $self->{squid_port} -j ACCEPT");
		run_script("$ck{iptables} -$rule_type OUTPUT -p tcp -d $ip --sport $self->{squid_port} -j ACCEPT");
	}
}


sub getCurrentSquidPort
{
	my ($self) = (shift);
	$self->{squid_port} = '';
	my $gw = &getCurrentDefaultGW;
	my $squid_settings = $self->getSquidsSettings();
	foreach my $v (values %$squid_settings)
	{
		$self->{squid_port} = $v->{port} if ($v->{enabled});
#		$self->{squid_port} = $v->{port} if ($gw eq $v->{inf} && $v->{enabled});
	}
	return $self->{squid_port};
}

return 1;
END {}
